package com.example.demo.service.exam.impl;

import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.domain.CombineClause;
import com.example.demo.domain.SingleClause;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.exam.FilePath;
import com.example.demo.exception.ExceptionUtils;
import com.example.demo.mapper.FilePathMapper;
import com.example.demo.service.exam.FilePathService;
import com.example.demo.service.impl.BaseServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FilePathServiceImpl extends BaseServiceImpl<FilePathMapper, FilePath> implements FilePathService {

    private final FilePathMapper mapper;

    @Override
    public void insert(FilePath entity) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        User user = userInfo.getUser();
        entity.setUserId(user.getId());
        valid(entity);
        mapper.insert(entity);
    }

    @Override
    public List<FilePath> getByExamUserId(Long examId, Long userId) {
        Optional.ofNullable(examId).orElseThrow(() -> ExceptionUtils.exception("用户标识不能为空"));
        Optional.ofNullable(userId).orElseThrow(() -> ExceptionUtils.exception("用户标识不能为空"));
        return super.selectList(CombineClause.and(
                SingleClause.equal("exam_id", examId),
                SingleClause.equal("user_id", userId)
        ));
    }

    @Override
    public Map<Long, List<FilePath>> getByUserIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Collections.emptyMap();
        }
        return super.selectList(SingleClause.in("user_id", userIds.toArray(new Object[0]))).stream()
                .collect(Collectors.groupingBy(FilePath::getUserId));
    }

    private void valid(FilePath entity) {

        Long userId = entity.getUserId();
        Long examId = entity.getExamId();
        String url = entity.getUrl();
        if (userId == null) {
            throw ExceptionUtils.exception("用户标识不能为空");
        }
        if (examId == null) {
            throw ExceptionUtils.exception("考试标识不能为空");
        }
        if (StringUtils.isBlank(url)) {
            throw ExceptionUtils.exception("文件路径不能为空");
        }
    }

}
